<template>
  <div class="container">
    <el-row>
      <el-col class="top-search">
        <el-select
          :placeholder="$t('please_select')"
          v-model="listQuery.newsType"
          class="w-180"
        >
          <el-option :value="null" :label="$t('content_types')" />
          <el-option :value="1" :label="$t('image_text')" />
          <el-option :value="2" :label="$t('photo_album')" />
          <el-option :value="3" :label="$t('video')" />
          <el-option :value="8" :label="$t('Short_video')" />
          <el-option :value="5" :label="$t('micro_headlines')" />
        </el-select>

        <el-select
          :placeholder="$t('please_select')"
          v-model="listQuery.isApprove"
          class="w-180"
        >
          <el-option :value="null" :label="$t('status')" />
          <el-option :value="0" :label="$t('audit_pending')" />
          <el-option :value="1" :label="$t('audit_accept')" />
          <el-option :value="2" :label="$t('drop_out')" />
        </el-select>

        <el-input
          :value="listQuery.authorId"
          @input="value => (listQuery.authorId = value.replace(/[^\d]/g, ''))"
          :maxlength="MaxMemberIdLength"
          :placeholder="$t('please_input_member_id')"
          clearable
          class="w-180"
        />

        <el-input
          v-model="listQuery.authorName"
          :placeholder="$t('please_enter_member_nickname')"
          clearable
          class="w-240"
        />

        <el-input
          :value="listQuery.authorMobile"
          @input="
            value => (listQuery.authorMobile = value.replace(/[^\d]/g, ''))
          "
          :placeholder="$t('please_input_mobile_phone_number')"
          clearable
          class="w-180"
        />

        <el-select
          v-model="listQuery.approveUserId"
          clearable
          filterable
          :placeholder="$t('please_select_an_auditor')"
        >
          <el-option
            v-for="item in approveUserOptions"
            :key="item.id"
            :label="item.userName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <br />

        <el-select
          :placeholder="$t('please_select')"
          v-model="listQuery.hasTag"
          class="w-180"
        >
          <el-option :value="0" :label="$t('with_or_without_tags')" />
          <el-option :value="1" :label="$t('has_tags')" />
          <el-option :value="2" :label="$t('no_tag')" />
        </el-select>

        <el-select
          :placeholder="$t('please_select')"
          v-model="listQuery.isPush"
          class="w-180"
        >
          <el-option :value="null" :label="$t('push_or_not')" />
          <el-option :value="1" :label="$t('pushed')" />
          <el-option :value="-1" :label="$t('not_pushed')" />
        </el-select>

        <treeselect
          v-model="newsTagIds"
          :multiple="true"
          :options="newsTagList"
          :placeholder="$t('select_information_tab')"
          :flat="true"
          :default-expand-level="1"
          :normalizer="normalizer"
          :limit-text="
            count => `${$t('Selected_xx_hashtag').replace('xx', count)}`
          "
          :no-options-text="$t('No_options_select')"
          value-consists-of="LEAF_PRIORITY"
          style="display:inline-block;vertical-align: middle;width:255px;"
        />

        <el-autocomplete
          v-model="subjectName"
          :fetch-suggestions="searchSubject"
          :trigger-on-focus="false"
          :placeholder="$t('please_search_and_select_the_subject')"
          clearable
          class="w-200"
          @clear="clear('subjectId')"
          @select="item => handleSelect(item, 'subjectId')"
        />

        <el-autocomplete
          v-model="topicName"
          :fetch-suggestions="searchTopic"
          :trigger-on-focus="false"
          :placeholder="$t('please_search_and_select_the_topic')"
          clearable
          class="w-200"
          @clear="clear('topicId')"
          @select="item => handleSelect(item, 'topicId')"
        />

        <el-input
          v-model="listQuery.subjectName"
          :placeholder="$t('special_page_name')"
          clearable
          class="w-180"
        />
        <el-input
          v-model="listQuery.topicName"
          :placeholder="$t('topic_related_words')"
          clearable
          class="w-180"
        />
        <el-input
          v-model="listQuery.title"
          :placeholder="$t('title_name')"
          clearable
          class="w-180"
        />
        <el-input
          :value="listQuery.id"
          @input="value => (listQuery.id = value.replace(/[^\d]/g, ''))"
          :placeholder="$t('content_id')"
          clearable
          class="w-180"
        />
        <br />

        <label for="">{{ $t('release_time') }}:</label>
        <el-date-picker
          v-model="datePicker1"
          class="w-240"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
          :start-placeholder="$t('el.datepicker.startDate')"
          :end-placeholder="$t('el.datepicker.endDate')"
        />
        <label for="">{{ $t('push_time') }}:</label>
        <el-date-picker
          v-model="datePicker2"
          class="w-240"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
          :start-placeholder="$t('el.datepicker.startDate')"
          :end-placeholder="$t('el.datepicker.endDate')"
        />
        <el-button type="primary" @click="search">
          {{ $t('search') }}
        </el-button>
        <el-button type="primary" @click="reset"> {{ $t('reset') }} </el-button>
        <el-button
          type="primary"
          :disabled="exportLoading"
          :loading="exportLoading"
          @click="toExport('exportLoading')"
          :title="$t('only_export_up_to_50000_data')"
        >
          {{ $t('export_doc') }}
        </el-button>
        <el-button
          type="primary"
          :disabled="exportOneDayLoading"
          :loading="exportOneDayLoading"
          @click="toExport('exportOneDayLoading', true)"
        >
          {{ $t('publish_24hour_data_export') }}
        </el-button>
      </el-col>

      <el-col class="p-t-15">
        <el-menu
          :default-active="listQuery.lan"
          class="el-menu-demo"
          mode="horizontal"
          @select="switchTab"
        >
          <el-menu-item index="km-KH">{{ $t('english_khmer') }}</el-menu-item>
          <el-menu-item index="zh-Hans">{{ $t('zh_hans') }}</el-menu-item>
        </el-menu>
      </el-col>

      <el-col class="p-t-20">
        <el-table
          v-loading="listLoading"
          :data="listData"
          border
          fit
          highlight-current-row
          @sort-change="apprenticeSortChange"
        >
          <el-table-column :label="$t('content_id')" prop="id" align="center" />

          <el-table-column
            :label="$t('content_cover')"
            align="center"
            width="220"
          >
            <template slot-scope="{ row }">
              <div class="pointer" @click="preview(row)">
                <img
                  v-if="row.newsType === 8"
                  :src="
                    row.thumbs && row.thumbs.indexOf(';') > -1
                      ? row.thumbs.split(';')[0]
                      : row.thumbs
                  "
                  :onerror="nonePic2"
                  class="shortvideo-image"
                />
                <img
                  v-else
                  :src="
                    row.thumbs && row.thumbs.indexOf(';') > -1
                      ? row.thumbs.split(';')[0]
                      : row.thumbs
                  "
                  :onerror="nonePic1"
                  class="news-image"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column :label="$t('push_time')" align="center" width="220">
            <template slot-scope="{ row }">
              <div v-if="row.pushTime && row.pushTime.length > 0">
                <p v-for="(item, index) in row.pushTime" :key="index">
                  {{ item | fmtdate }}
                </p>
                <br />
              </div>
              <p v-else>{{ $t('none') }}</p>
            </template>
          </el-table-column>

          <el-table-column :label="$t('content_information')" width="460">
            <template slot-scope="{ row }">
              <div>
                <p class="title" v-html="row.title"></p>
                <p>
                  <span class="m-r-10"
                    >{{ $t('release') }} : {{ row.authorName }}
                  </span>
                  <span>{{ $t('review') }} : {{ row.approveUserName }} </span>
                </p>
                <p>
                  <span class="m-r-10">{{ newsTypeMap[row.newsType] }} </span>
                  <span>{{ $t('release_time') }} : {{ row.releaseTime }} </span>
                </p>
                <p>
                  <span class="m-r-10"
                    >{{ $t('like') }} : {{ row.praiseCount || 0 }}
                  </span>
                  <span class="m-r-10"
                    >{{ $t('comment') }} : {{ row.reviewCount || 0 }}
                  </span>
                  <span class="m-r-10"
                    >{{ $t('favorites') }} : {{ row.collectCount || 0 }}
                  </span>
                  <span class="m-r-10"
                    >{{ $t('share') }} : {{ row.shareCount || 0 }}
                  </span>
                </p>
                <p>
                  <span
                    >{{ $t('tag') }}: {{ row.typeTagsFlat || $t('none') }}</span
                  >
                </p>
                <p>
                  <span
                    >{{ $t('special_page') }}:
                    {{ row.subjectNameFlat || $t('none') }}</span
                  >
                </p>
                <p>
                  <span
                    >{{ $t('topic') }}:
                    {{ row.topicNameFlat || $t('none') }}</span
                  >
                </p>
                <p>
                  <span>{{ $t('score') }}: {{ row.score || $t('none') }}</span>
                </p>
                <p>
                  <span
                    >{{ $t('publisher_type') }} :
                    {{ $t(authorTypeMap[row.authorType]) }}</span
                  >
                </p>
                <p>
                  <span>
                    {{ $t('push_condition') }}：
                    {{
                      row.isPush == 1 ? $t('pushed') : $t('not_pushed')
                    }}</span
                  >
                  <span v-if="row.isPush == 1">
                    {{ $t('push_hits') }}： {{ row.pushReachCount }}
                  </span>
                </p>
              </div>
            </template>
          </el-table-column>

          <el-table-column :label="$t('status')" align="center">
            <template slot-scope="{ row }">
              <span> {{ statusMap[row.isApprove] }} </span>
            </template>
          </el-table-column>

          <el-table-column
            sortable="custom"
            :label="$t('real_heat')"
            prop="realHotValue"
            align="center"
          />

          <el-table-column
            sortable="custom"
            :label="$t('yesterday_recommended_pv')"
            prop="yesterdayRecommendPv"
            align="center"
          />
          <el-table-column
            sortable="custom"
            :label="$t('yesterday_exposure_pv')"
            prop="yesterdayShowPv"
            align="center"
          />
          <el-table-column
            sortable="custom"
            :label="$t('cumulative_recommended_pv')"
            prop="totalRecommendPv"
            align="center"
          />
          <el-table-column
            sortable="custom"
            :label="$t('cumulative_exposure_pv')"
            prop="totalShowPv"
            align="center"
          />
          <el-table-column
            sortable="custom"
            :label="$t('reading')"
            prop="totalReadCounts"
            align="center"
          />
          <el-table-column
            sortable="custom"
            :label="$t('exposure_to_reading_conversion_rate')"
            prop="showReadRate"
            align="center"
          >
            <template slot-scope="{ row }">
              <span> {{ row.showReadRate | percentageBydecima }} </span>
            </template>
          </el-table-column>

          <el-table-column :label="$t('operation')" align="center" width="240">
            <template slot-scope="{ row }">
              <el-button type="primary" @click="preview(row)">
                {{ $t('preview') }}
              </el-button>
              <el-button type="primary" @click="goDetails(row.id)">
                {{ $t('detailed_analysis') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="total > 0" class="block fr">
          <el-pagination
            :current-page="listQuery.page"
            :page-sizes="[15, 20, 30]"
            :page-size="listQuery.size"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="val => handlePageChange(val, 'size')"
            @current-change="val => handlePageChange(val, 'page')"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 预览 -->
    <Preview
      v-if="previewData.newsType !== ''"
      v-model="previewData.newsType"
      :news-id="previewData.newsId"
      :lan="previewData.lan"
    />
  </div>
</template>

<script>
import { CONTENT_AUTHOR_TYPE_MAP } from '@/constants/index';
import {
  getContentListApi,
  getSubjectListApi,
  getTopicListApi,
  getTagListApi,
  getApproveListApi
} from '@/api/information-content-analysis.js';
import Preview from '@/components/preview/index.vue';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { getALLTags } from '@/api/preview.js';
import { getToken } from '@/utils/auth';
import { de } from 'date-fns/locale';
import { format } from 'date-fns';
import timeUtils from '@/utils/timeHandle.js';

const MaxMemberIdLength = 18;
const INIT_LISTQUERY = {
  lan: 'km-KH',
  isPush: null, // -1 未推送 1已推送
  newsType: null, // 1图文，2图集，3视频，5微头条，8小视频
  isApprove: null, // 0未审核，1已发表，2下架，3草稿
  authorId: null,
  authorName: null,
  authorMobile: null,
  hasTag: 0,
  newsTags: [],
  dynamicTags: [],
  smallvideoTags: [],
  subjectId: null,
  topicId: null,
  title: null,
  id: null,
  beginReleaseTime: null,
  endReleaseTime: null,
  beginPushTime: null,
  endPushTime: null,
  size: 15,
  page: 1,
  orderBy: 0,
  asc: false,
  approveUserId: null
};

export default {
  components: {
    Preview,
    Treeselect
  },

  data() {
    return {
      MaxMemberIdLength,
      datePicker1: [
        timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24, 'date'),
        timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24, 'date')
      ],
      datePicker2: [],
      listLoading: false,
      exportLoading: false,
      exportOneDayLoading: false,
      listQuery: {
        ...INIT_LISTQUERY
      },
      listData: [],
      total: 0,
      statusMap: {
        0: this.$t('audit_pending'),
        1: this.$t('audit_accept'),
        2: this.$t('drop_out'),
        3: this.$t('draft')
      },
      newsTypeMap: {
        1: this.$t('image_text'),
        2: this.$t('photo_album'),
        3: this.$t('video'),
        5: this.$t('micro_headlines'),
        8: this.$t('Short_video')
      },
      authorTypeMap: CONTENT_AUTHOR_TYPE_MAP,
      previewData: {
        newsId: '',
        newsType: '',
        title: '',
        time: ''
      },
      nonePic1:
        'this.onerror=null;this.src="' +
        require('@/assets/images/nopicture226x140.png') +
        '"',
      nonePic2:
        'this.onerror=null;this.src="' +
        require('@/assets/images/nopicture366x550.png') +
        '"',
      newsTagIds: [],
      newsTagList: [],
      newsTagArray: [],

      normalizer(node) {
        return {
          id: node.id,
          label: node.tagName,
          children: node.children
        };
      },
      subjectName: null,
      topicName: null,
      selectObj: {
        subjectId: null,
        topicId: null
      },
      approveUserOptions: []
    };
  },

  filters: {
    percentageBydecima(val) {
      if (!val || val == 0) {
        return 0;
      }

      return `${(val * 100).toFixed(2)}%`;
    }
  },

  created() {
    const { memberId } = this.$route.query;
    if (memberId) {
      this.listQuery.authorId = memberId;
      this.datePicker1 = [];
    }
    this.getNewsTagList();
    this.getApproveList();
    this.search();
  },

  methods: {
    async getApproveList() {
      try {
        const { code, data } = await getApproveListApi();
        if (code === 200) {
          this.approveUserOptions = data || [];
        }
      } catch (e) {
        this.approveUserOptions = [];
      }
    },

    // 没有三级标签的为微头条标签 需要过滤掉 这里只显示资讯标签
    async getNewsTagList() {
      const newsTagArray = [];
      let zh = [];
      let km = [];

      try {
        const { state, result } = await getALLTags();
        if (state == 1) {
          result.forEach(item => {
            item.children
              .filter(childItem => {
                return (
                  childItem.children != null && childItem.children.length != 0
                );
              })
              .forEach(childItem => {
                const obj = {
                  id: childItem.id,
                  tagName: childItem.tagName,
                  children: childItem.children
                };
                item.id == -1 ? zh.push(obj) : km.push(obj);
                newsTagArray.push({
                  id: childItem.id,
                  tagName: childItem.tagName
                });
                childItem.children.forEach(lastItem => {
                  newsTagArray.push({
                    id: lastItem.id,
                    tagName: lastItem.tagName
                  });
                  if (lastItem.children == null) {
                    delete lastItem.children;
                  }
                });
              });
          });

          this.newsTagArray = newsTagArray;
          this.newsTagList = [
            {
              id: -1,
              tagName: this.$t('chinese_information_label'),
              children: zh
            },
            {
              id: -2,
              tagName: this.$t('cambodian_information_label'),
              children: km
            }
          ];
        }
      } catch (e) {
        throw e;
      }
    },

    search() {
      const { datePicker1, datePicker2, newsTagArray, newsTagIds } = this;
      const beginReleaseTime = (datePicker1 && datePicker1[0]) || null;
      const endReleaseTime = (datePicker1 && datePicker1[1]) || null;
      const beginPushTime = (datePicker2 && datePicker2[0]) || null;
      const endPushTime = (datePicker2 && datePicker2[1]) || null;

      const newsTags = newsTagArray
        .filter(item => newsTagIds.includes(item.id))
        .map(item => {
          const { id: tagId, tagName } = item;
          return { tagId, tagName };
        });

      this.listQuery = {
        ...this.listQuery,
        ...this.selectObj,
        beginReleaseTime,
        endReleaseTime,
        beginPushTime,
        endPushTime,
        newsTags,
        page: 1
      };
      this.subjectName = this.selectObj.subjectId ? this.subjectName : null;
      this.topicName = this.selectObj.topicId ? this.topicName : null;
      this.getList();
    },

    async getList() {
      if (this.listLoading) return;
      this.listLoading = true;

      try {
        const { code, data } = await getContentListApi(this.listQuery);
        this.listLoading = false;
        if (code == 200) {
          this.listData = data.list || [];
          this.total = Number(data.count) || 0;
        }
      } catch (e) {
        this.listLoading = false;
      }
    },

    reset() {
      this.listQuery = {
        ...INIT_LISTQUERY
      };

      this.selectObj = {
        subjectId: null,
        topicId: null
      };

      this.datePicker1 = [
        timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24, 'date'),
        timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24, 'date')
      ];
      this.datePicker2 = [];
      this.newsTagIds = [];
      this.subjectName = null;
      this.topicName = null;
    },

    async searchTopic(queryString, cb) {
      this.selectObj.subjectId = null;
      const query = {
        title: queryString,
        pageNum: 1,
        pageSize: 100
      };

      try {
        const { state, result, error_msg } = await getTopicListApi(query);
        if (state == 1) {
          if (!result.list || result.list.length == 0) {
            cb([]);
            this.$message.warning(this.$t('no_match_please_reenter'));
            this.topicName = null;
          } else {
            const arr = result.list.map(item => {
              item.value = item.title;
              return item;
            });
            cb(arr);
          }
        } else {
          setTimeout(() => {
            cb([]);
            this.$message.warning(error_msg);
          }, 500);
        }
      } catch (e) {
        setTimeout(() => {
          cb([]);
        }, 500);
      }
    },

    async searchSubject(queryString, cb) {
      this.selectObj.subjectId = null;
      const query = {
        keyword: queryString,
        pageNum: 1,
        pageSize: 100
      };

      try {
        const { state, result, error_msg } = await getSubjectListApi(query);
        if (state == 1) {
          if (!result.list || result.list.length == 0) {
            cb([]);
            this.$message.warning(this.$t('no_match_please_reenter'));
            this.subjectName = null;
          } else {
            const arr = result.list.map(item => {
              item.value = item.specialName;
              return item;
            });
            cb(arr);
          }
        } else {
          setTimeout(() => {
            cb([]);
            this.$message.warning(error_msg);
          }, 500);
        }
      } catch (e) {
        setTimeout(() => {
          cb([]);
        }, 500);
      }
    },

    switchTab(val) {
      this.listQuery.lan = val;
      this.search();
    },

    handlePageChange(val, name) {
      this.listQuery[name] = val;
      this.getList();
    },

    preview({ id, newsType }) {
      this.previewData = { ...this.previewData, newsId: id, newsType };
    },

    goDetails(newsId) {
      const url = `${
        process.env.DATA_ADMIN
      }/#/ContentListData/contentDetail?newsId=${newsId}`;
      window.open(url);
    },

    apprenticeSortChange({ column, prop, order }) {
      let asc;
      let orderBy;
      if (!order) {
        asc = true;
        orderBy = 0;
      } else {
        const map = {
          realHotValue: 1,
          yesterdayRecommendPv: 2,
          yesterdayShowPv: 3,
          totalRecommendPv: 4,
          totalShowPv: 5,
          totalReadCounts: 6,
          showReadRate: 7
        };

        orderBy = map[prop];
        asc = order == 'descending' ? false : true;
      }

      this.listQuery = { ...this.listQuery, asc, orderBy };
      this.search();
    },

    clear(key) {
      this.selectObj[key] = null;
    },

    handleSelect(item, key) {
      this.selectObj[key] = item.id;
    },

    // 导出结果保存和上次列表搜索结果一致
    toExport(loading, isOneDay) {
      const url = isOneDay
        ? '/v1/analysis/newsContentExport24'
        : '/v1/analysis/newsContentExport';
      const time = format(new Date(), 'yyyy-MM-dd HH-mm-ss');
      const fileName = isOneDay
        ? `${this.$t('publish_24hour_data')} ${time}.xls`
        : `${time}.xls`;
      const that = this;
      if (that[loading]) return;
      that[loading] = true;
      const language = that.$store.state.app.language || 'zh';
      const lanMap = {
        zh: 'zh-Hans',
        en: 'en-US',
        km: 'km-KH'
      };
      const lan = lanMap[language];

      var xhh = new XMLHttpRequest();
      xhh.open('post', process.env.BASE_API + url);
      xhh.setRequestHeader('X-Token', getToken());
      xhh.setRequestHeader('lan', lan);
      xhh.setRequestHeader('content-type', 'application/json;charset=UTF-8');
      xhh.responseType = 'blob';
      xhh.onreadystatechange = function() {
        if (xhh.readyState === 4 && xhh.status !== 200) {
          that.$message.warning('导出出错');
          that[loading] = false;
        }
        if (xhh.readyState === 4 && xhh.status === 200) {
          var blob = new Blob([xhh.response]);
          var csvUrl = URL.createObjectURL(blob);
          var link = document.createElement('a');
          document.body.appendChild(link);
          link.href = csvUrl;
          link.target = '_blank';
          link.id = 'linkId';
          link.className = 'linkId';
          link.download = decodeURI(fileName);
          document.getElementById('linkId').click();
          link.remove();
          that[loading] = false;
        }
      };
      const query = { ...this.listQuery, page: 1, size: 50000 };
      xhh.send(JSON.stringify(query));
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;

  .top-search {
    margin: 10px 0;

    label {
      font-size: 12px;
      font-weight: 400;
      margin-right: 5px;
    }
  }

  .w-120 {
    width: 120px;
  }

  .w-180 {
    width: 180px;
  }

  .w-240 {
    width: 240px;
  }

  .w-400 {
    width: 400px;
  }

  .p-t-20 {
    padding-top: 20px;
  }

  .m-l-10 {
    margin-left: 10px;
  }

  .fr {
    float: right;
    padding-top: 20px;
  }

  .news-image {
    width: 200px;
    height: 140px;
    object-fit: cover;
  }

  .shortvideo-image {
    width: 167px;
    height: 250px;
    object-fit: cover;
  }

  .pointer {
    cursor: pointer;
  }

  .title {
    width: 440px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
  }
}

.container /deep/ .el-loading-spinner {
  top: 10%;
}
</style>
